package com.zhang.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhang.domain.Users;
import com.zhang.mapper.UserMapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MyUserDetailService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //一 根据用户名查询用户
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        Users users = userMapper.selectOne(wrapper);
        if(users == null){
            throw  new UsernameNotFoundException("用户名不存在!");
        }


        //二 封装user
        //1.用户名
        username = users.getUsername();
        //2.密码(进行加密)
        String password = new BCryptPasswordEncoder().encode(users.getPassword());
        //3.封装权限集合
        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("bbb");

        //3.返回user (这个User是Security提供的 , 并且它实现UserDetails接口)
        return new User(username,password,auths);
    }
}




